package com.zonerobotics.tutorial.btcontrol;
import java.util.Set;

import com.zonerobotics.tutorial.btcontrol.R;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	
    // Debugging
    private static final String TAG = "MainAct";
    private static final boolean D = true;
    
    // constants 
    public static final int SCAN_FOR_BTBOTS = 10;
 // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    public static final int ADD_BTBOT = 0;
    
    // members
    private BluetoothAdapter mBtAdapter;
    private ListView mListViewBots;
    private ArrayAdapter<String> mArrayAdapterBots;
    private BluetoothDevice mDevice;
    
    // view changing
    //ViewFlipper vf = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// setup bluetooth, make sure its on etc
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		
		// setup the list view of bots
		mArrayAdapterBots = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		mListViewBots = (ListView)findViewById(R.id.listMainBots);
		mListViewBots.setAdapter(mArrayAdapterBots);
		mListViewBots.setOnItemClickListener(mDeviceClickListener);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.addbt:
	        	scanForBTBots();
	            return true;
	        case R.id.addinet:
	        	//Intent i = new Intent(this, ScanForBots.class);
	        	//startActivity(i);
	        	// todo list bots from server
	            return true;

	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public void addBot(String info)
	{
		mArrayAdapterBots.add(info);
	}
	
	public void scanForBTBots()
	{
    	if(mBtAdapter == null)
    	{
    		Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
    		return;
    	}
    	Toast.makeText(this, "Please add and pair now", Toast.LENGTH_LONG).show();
    	Intent intentBluetooth = new Intent();
        intentBluetooth.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
        startActivity(intentBluetooth);
    	// todo below later for now just let them use system/settings above
        /*
    	if(!mBtAdapter.isEnabled())
    	{
    		startEnableBlueTooth();
    		return;
    	}
		Intent i = new Intent(this, BTScanForBots.class);
    	startActivityForResult(i, SCAN_FOR_BTBOTS);
    	*/
	}
	
	public void startGameActivity(String devAddr)
	{
    	Intent i = new Intent(this, ControlbotActivity.class);
        i.putExtra("devAddr", devAddr);
        startActivity(i);
	}
	
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
          
        	// if its add a new bot do it, else they are wanting to play with a 
        	// current bot
        	if(arg3 == ADD_BTBOT)
        	{
        		scanForBTBots();
        	}else{ // else they clicked a bot, use it to play
        		// todo ensure its actually a string with this len!
                String info = ((TextView) v).getText().toString();
                String address = info.substring(info.length() - 17);
        		startGameActivity(address);
        		
        	}
            // Get the device MAC address, which is the last 17 chars in the View
            //String info = ((TextView) v).getText().toString();
            
        }
    };
	
	public void listBTBots()
	{
		// todo add initial bots to array adapter
		// from db or whatever
		// todo get status of bot, is it online ? is it a bot ? 
		mArrayAdapterBots.clear();
		
		mArrayAdapterBots.add("Add New Bot");
		//mArrayAdapterBots.add("TestBot");
		
		// if we have an adapter get already paired devices
		if(mBtAdapter != null)
		{
	        // Get a set of currently paired devices
	        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
	
	        // If there are paired devices, add each one to the ArrayAdapter
	        if (pairedDevices.size() > 0) {
	            for (BluetoothDevice device : pairedDevices) {
	            	mArrayAdapterBots.add(device.getName() + "\n" + device.getAddress());
	            }
	        }
		}
	}
	
	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
	  super.onActivityResult(requestCode, resultCode, data); 
	  switch(requestCode) { 
	    // we scanned for new bots
	    case (SCAN_FOR_BTBOTS) : { 
	    	String newBotInfo = data.getStringExtra("NEW_BOT");
	    	if(newBotInfo != null)
	    	{
	    		addBot(newBotInfo);
	    	}
	      break; 
	    }
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
            	Log.d(TAG, "adding connect dev");
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, check and list previous bots
            	listBTBots();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, "Bluetooth bots will not be available", Toast.LENGTH_SHORT).show();
                finish();
            }
	  } 
	}

    
    public void startEnableBlueTooth()
    {
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        if(mBtAdapter != null)
        {
	        // If BT is not on, request that it be enabled.
	        // setupChat() will then be called during onActivityResult
	        if (!mBtAdapter.isEnabled()) {
	            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
	        // Otherwise, setup the chat session
	        } else {
	            // bt is enabled we are ready to get bot status
	        	listBTBots();
	        }
        }else{
        	Toast.makeText(this, "Bluetooth bots will not be available", Toast.LENGTH_SHORT).show();
        }
        
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "- ON RESUME -");
        listBTBots();
    }
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

}
